package com.nmdl.print.utils;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.nmdl.print.R;

import java.util.ArrayList;
import java.util.List;

public class DevicesAdapter extends RecyclerView.Adapter<DevicesAdapter.ViewHolder> {
    List<BluetoothDevice> bluetoothDeviceList = new ArrayList<>();
    ItemClickListener itemclickListener;
    Context context;

    public DevicesAdapter(Context context, ItemClickListener itemclickListener) {
        this.context = context;
        this.itemclickListener = itemclickListener;
    }

    public List<BluetoothDevice> getData() {
        return bluetoothDeviceList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_blue_tooth, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        BluetoothDevice mBlueDevice = bluetoothDeviceList.get(position);
        holder.device_name_tv.setText("名称: " + mBlueDevice.getName());
        holder.connect_device_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                holder.connect_device_btn.setEnabled(false);
                itemclickListener.connectClick(bluetoothDeviceList.get(position));
            }
        });
    }

    @Override
    public int getItemCount() {
        return bluetoothDeviceList.size();
    }

    public void addData(BluetoothDevice device) {
        bluetoothDeviceList.add(device);
        notifyDataSetChanged();
    }

    public interface ItemClickListener {
        void connectClick(BluetoothDevice position);
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView device_name_tv;
        Button connect_device_btn;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            device_name_tv = itemView.findViewById(R.id.device_name_tv);
            connect_device_btn = itemView.findViewById(R.id.connect_device_btn);
        }
    }
}
